use actix_web::{web, App, HttpServer, Responder};
use std::cell::Cell;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
    count: Cell<usize>,
    global_count: Arc<AtomicUsize>,
}

async fn show_count(data: web::Data<AppState>) -> impl Responder {
    format!(
        "global_count:{}\nlocal_count: {}",
        data.global_count.load(Ordering::SeqCst),
        data.count.get()
    )
}

async fn add_one(data: web::Data<AppState>) -> impl Responder {
    let count = data.count.get();
    data.count.set(count + 1);
    data.global_count.fetch_add(1, Ordering::SeqCst);

    format!("count: {}", data.count.get())
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let data = AppState {
        count: Cell::new(0),
        global_count: Arc::new(AtomicUsize::new(0)),
    };

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(data.clone()))
            .route("/show_count", web::to(show_count))
            .route("/add_one", web::to(add_one))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
